package com.asura.app.wechat.repository;

import com.asura.app.library.utils.ExecutorHelper;
import com.asura.app.wechat.common.WechatModuleProvider;
import com.asura.app.wechat.repository.datasource.MomentDataSource;
import com.asura.app.wechat.repository.model.Tweet;
import com.asura.app.wechat.repository.net.WechatApi;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Single;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Asura on 2017/12/29.
 */

public class MomentRemoteDataSource implements MomentDataSource {
    private WechatApi wechatApi;

    public MomentRemoteDataSource() {
        wechatApi = WechatModuleProvider.getInstance().getWechatApi();
    }

    @Override
    public Single<List<Tweet>> getTweets(String startId, int limit) {
        return wechatApi
                .fetchMomentTweets()
                .map(new Function<List<Tweet>, List<Tweet>>() {
                    @Override
                    public List<Tweet> apply(List<Tweet> tweets) throws Exception {
                        int count = 0;
                        List<Tweet> result = new ArrayList<>();
                        for (Tweet tweet : tweets) {
                            if (tweet.getSender() != null && (tweet.getContent() != null || tweet.getImages() != null)) {
                                if (tweet.getId() == null) {
                                    tweet.setId((count++) + "");
                                }
                                result.add(tweet);
                            }
                        }
                        return result;
                    }
                })
                .subscribeOn(Schedulers.from(ExecutorHelper.HIGH));
    }
}
